<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="浏览器缓存机制：强缓存&amp;协商缓存, code">
    <meta name="description" content="Record my graduate life">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>浏览器缓存机制：强缓存&amp;协商缓存 | Precious Life</title>
    <link rel="icon" type="image/png" href="/medias/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="Precious Life" type="application/atom+xml">
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Precious Life</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Precious Life</div>
        <div class="logo-desc">
            
            Record my graduate life
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/5.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">浏览器缓存机制：强缓存&amp;协商缓存</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C/">
                                <span class="chip bg-color">计算机网络</span>
                            </a>
                        
                            <a href="/tags/%E5%BC%BA%E7%BC%93%E5%AD%98-%E5%8D%8F%E5%95%86%E7%BC%93%E5%AD%98/">
                                <span class="chip bg-color">强缓存&amp;协商缓存</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E5%89%8D%E7%AB%AF%E7%AC%94%E8%AE%B0/" class="post-category">
                                前端笔记
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-11-23
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2021-11-23
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    3.7k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    13 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="说明"><a href="#说明" class="headerlink" title="#说明"></a>#说明</h2><blockquote>
<p>浏览器缓存策略对于我们前端来说应该算是必须要会的知识点,但如果没有系统地进行归纳总结,也很难三言两语说明白甚至说错;特别是在面试时,基本上就讲个概念,甚至有时候就忘掉了,所以整理一下,也为了以后遗忘时能快速复习</p>
<p>查阅借鉴的资料: 掘金的 <a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903838768431118">http面试必会的：强制缓存和协商缓存</a>、<a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903747357769742?utm_source=gold_browser_extension">一文读懂前端缓存</a>、<a target="_blank" rel="noopener" href="https://juejin.cn/post/6947936223126093861">前端浏览器缓存知识梳理</a>;Github的 <a target="_blank" rel="noopener" href="https://github.com/amandakelake/blog/issues/41#">缓存（二）——浏览器缓存机制：强缓存、协商缓存</a>;机器之心的 <a target="_blank" rel="noopener" href="https://www.jiqizhixin.com/articles/2020-07-24-12">彻底弄懂浏览器缓存策略</a></p>
</blockquote>
<h2 id="1、前端缓存"><a href="#1、前端缓存" class="headerlink" title="1、前端缓存"></a>1、前端缓存</h2><blockquote>
<p>当我们第一次访问网站时,电脑会把网站上的图片与数据下载到电脑上,当我们再次访问该网站时,网站就会从电脑中直接加载出来,这就是缓存</p>
<ul>
<li>web缓存是指一个Web资源(如html页面、图、JS等)存在于web服务器和客户端(浏览器)之间的副本</li>
<li>缓存会根据进来的请求保存输出内容的副本: 当下一个请求来到的时候,如果是相同的Url,缓存会根据缓存机制决定是直接使用副本响应访问请求还是像源服务器再次发起请求</li>
</ul>
</blockquote>
<h3 id="Ⅰ-缓存有哪些好处"><a href="#Ⅰ-缓存有哪些好处" class="headerlink" title="Ⅰ - 缓存有哪些好处"></a>Ⅰ - 缓存有哪些好处</h3><blockquote>
<ul>
<li>缓解服务端压力,不用每次都去请求某些数据</li>
<li>提升性能,打开本地资源肯定比请求服务器来的更快 </li>
<li>减少宽带消耗,当我们使用缓存的时候,只会产生很小的网络消耗,至于为什么打开本地资源也会产生网络消耗?</li>
</ul>
</blockquote>
<h3 id="Ⅱ-前端缓存种类"><a href="#Ⅱ-前端缓存种类" class="headerlink" title="Ⅱ - 前端缓存种类"></a>Ⅱ - 前端缓存种类</h3><blockquote>
<ol>
<li>数据库缓存</li>
<li>CDN缓存</li>
<li>代理服务器缓存</li>
<li>浏览器缓存</li>
</ol>
<p><strong>此图截取自网上相关文章</strong></p>
<p><img src="/2021/11/23/liu-lan-qi-huan-cun-ji-zhi-qiang-huan-cun-xie-shang-huan-cun/1.png" alt="不同缓存描述"></p>
</blockquote>
<h2 id="2、什么是浏览器缓存策略"><a href="#2、什么是浏览器缓存策略" class="headerlink" title="2、什么是浏览器缓存策略"></a>2、什么是浏览器缓存策略</h2><blockquote>
<p>良好的缓存策略可以降低资源的重复加载从而提高页面整体加载速度,通常浏览器缓存策略分为两种结果</p>
<ul>
<li>强缓存</li>
<li>协商缓存</li>
</ul>
<p><img src="/2021/11/23/liu-lan-qi-huan-cun-ji-zhi-qiang-huan-cun-xie-shang-huan-cun/2.png" alt="缓存"> </p>
</blockquote>
<h3 id="Ⅰ-基本原理"><a href="#Ⅰ-基本原理" class="headerlink" title="Ⅰ - 基本原理"></a>Ⅰ - 基本原理</h3><blockquote>
<ul>
<li>浏览器在加载资源时,根据请求头的 <code>Expires(过期时间)</code> 和<code>chche-control(缓存控制)</code>判断是否命中强缓存,命中则直接从缓存中读取资源,不会发送到服务器</li>
<li>如果没有命中强缓存,浏览器一定会发送一个请求到服务器,通过<code>last-modified</code>和<code>etag</code>验证资源是否命中协商缓存,如果命中,服务器回将这个请求返回,但是不会返回这个资源的数据,依然是从缓存中读取资源</li>
<li>如果前面两者都没有命中,则直接从服务器加载资源 </li>
</ul>
</blockquote>
<h3 id="Ⅱ-根据什么规则缓存"><a href="#Ⅱ-根据什么规则缓存" class="headerlink" title="Ⅱ - 根据什么规则缓存"></a>Ⅱ - 根据什么规则缓存</h3><blockquote>
<ol>
<li><strong>新鲜度</strong>(过期机制):也就是缓存副本有效期. 一个缓存副本必须满足以下条件,浏览器会认为它是有效的,足够新的</li>
</ol>
<ul>
<li>含有完整的过期时间控制头信息(HTTP协议报头),并且仍在有效期内</li>
<li>浏览器已经使用过这个缓存副本,并且在一个会话中已经检查过新鲜度</li>
<li><strong>通常是强缓存阶段使用的机制</strong></li>
</ul>
<ol start="2">
<li><strong>校验值</strong>(验证机制): 服务器返回资源的时候有时在控制头信息带上这个资源的实体标签<code>Etag</code>,</li>
</ol>
<ul>
<li>它可以用来作为浏览器再次请求过程的校验标识</li>
<li>如果发现校验标识不匹配,说明资源已经被修改或者过期,浏览器需要重新获取资源内容</li>
<li><strong>所以通常是协商缓存中使用的机制</strong></li>
</ul>
</blockquote>
<h3 id="Ⅲ-HTTP缓存的两个阶段"><a href="#Ⅲ-HTTP缓存的两个阶段" class="headerlink" title="Ⅲ - HTTP缓存的两个阶段"></a>Ⅲ - HTTP缓存的两个阶段</h3><blockquote>
<p>浏览器缓存一般分为两类: <strong>强缓存</strong>(也称本地缓存) 和 <strong>协商缓存</strong>(也称弱缓存)</p>
<h6 id="强缓存阶段"><a href="#强缓存阶段" class="headerlink" title="强缓存阶段"></a>强缓存阶段</h6><blockquote>
<p>浏览器发送请求前,会去缓存里查看是否命中强缓存,如果命中,则直接从缓存中读取资源,不会发送请求到服务器;</p>
</blockquote>
<h6 id="协商缓存阶段"><a href="#协商缓存阶段" class="headerlink" title="协商缓存阶段"></a>协商缓存阶段</h6><blockquote>
<p>当强缓存没有命中时,浏览器一定会向服务器发起请求</p>
</blockquote>
<blockquote>
<ul>
<li>服务器会根据 <code>request header</code> 中的一些字段来判断是否命中协商缓存</li>
<li>如果命中,服务端会返回304响应,但是不会携带任何响应实体,只是高速浏览器可以直接从浏览器缓存中获取这个资源</li>
<li>如果 <strong>强缓存</strong> 和 <strong>协商缓存</strong> 都没有命中,则直接从服务器加载资源</li>
</ul>
</blockquote>
<p><img src="/2021/11/23/liu-lan-qi-huan-cun-ji-zhi-qiang-huan-cun-xie-shang-huan-cun/3.png" alt="本地缓存也就是强缓存"> </p>
</blockquote>
<h3 id="Ⅳ-优先级"><a href="#Ⅳ-优先级" class="headerlink" title="Ⅳ - 优先级"></a>Ⅳ - 优先级</h3><blockquote>
<ul>
<li><code>Cache-Control</code>优先级大于 <code>expires</code></li>
<li><code>Etag</code> 优先级大于 <code>last - Modified/if-Modified-since</code>,同时存在时会以Etag为准</li>
</ul>
</blockquote>
<h3 id="Ⅴ-浏览器缓存流程图"><a href="#Ⅴ-浏览器缓存流程图" class="headerlink" title="Ⅴ - 浏览器缓存流程图"></a>Ⅴ - 浏览器缓存流程图</h3><blockquote>
<p><img src="/2021/11/23/liu-lan-qi-huan-cun-ji-zhi-qiang-huan-cun-xie-shang-huan-cun/4.png" alt="流程图"> </p>
</blockquote>
<h2 id="3、强缓存与协商缓存"><a href="#3、强缓存与协商缓存" class="headerlink" title="3、强缓存与协商缓存"></a>3、强缓存与协商缓存</h2><h3 id="Ⅰ-强缓存"><a href="#Ⅰ-强缓存" class="headerlink" title="Ⅰ - 强缓存"></a>Ⅰ - 强缓存</h3><blockquote>
<h6 id="通过Expires-过yu期-和cache-control-缓存控制器-两种响应头实现"><a href="#通过Expires-过yu期-和cache-control-缓存控制器-两种响应头实现" class="headerlink" title="通过Expires(过yu期)和cache-control(缓存控制器)两种响应头实现"></a>通过<code>Expires(过yu期)</code>和<code>cache-control(缓存控制器)</code>两种响应头实现</h6><p>浏览器在加载资源时,根据请求头的 <code>Expires(过期时间)</code> 和<code>chche-control(缓存控制)</code>判断是否命中强缓存,命中则直接从缓存中读取资源,不会发送到服务器</p>
</blockquote>
<h4 id="①-Expires-过期"><a href="#①-Expires-过期" class="headerlink" title="①  Expires(过期)"></a>①  Expires(过期)</h4><blockquote>
<p><code>Expires</code>是 http1.0 提出的表示资源过期时间的header, 它描述的是一个绝对时间,由服务端返回;当我们准备再次发起请求时,本地时间未超过这个设置的时间,那么就不会真正的发出请求,而是读取缓存</p>
<p>expires受限于本地时间,如果修改了本地时间,可能会造成缓存失效</p>
</blockquote>
<h4 id="②-cache-control"><a href="#②-cache-control" class="headerlink" title="②  cache-control"></a>②  cache-control</h4><blockquote>
<p><code>cache-control</code>出现于HTTP1.1, 优先级高于Expires ,表示的是相对时间</p>
<ul>
<li><code>cache-control:no-cache</code> 的响应实际上是可以存储在本地缓存去中的,只是在与原始服务器进行新鲜度再验证之前,缓存不能将其提供给客户端使用</li>
<li><code>Cache-Control: no-store</code> 真正的不缓存到本地</li>
<li><code>Cache-Control: public</code> 可以被所有用户缓存(多用户共享),包括终端和CDN等中间代理服务器</li>
<li><code>Cache-Control: private</code>只能被终端浏览器缓存（而且是私有缓存），不允许中继缓存服务器进行缓存</li>
</ul>
</blockquote>
<h3 id="Ⅱ-协商缓存"><a href="#Ⅱ-协商缓存" class="headerlink" title="Ⅱ - 协商缓存"></a>Ⅱ - 协商缓存</h3><blockquote>
<h6 id="协商缓存是通过【Last-Modified，If-Modified-Since】和【ETag、If-None-Match】这两对Header来管理的"><a href="#协商缓存是通过【Last-Modified，If-Modified-Since】和【ETag、If-None-Match】这两对Header来管理的" class="headerlink" title="协商缓存是通过【Last-Modified，If-Modified-Since】和【ETag、If-None-Match】这两对Header来管理的"></a>协商缓存是通过<code>【Last-Modified，If-Modified-Since】</code>和<code>【ETag、If-None-Match】</code>这两对Header来管理的</h6><ul>
<li>当浏览器对某个资源的请求没有命中强缓存(换句话说就是: <strong>强缓存失效后</strong>)</li>
<li>就会发一个请求到服务器,验证协商缓存是否命中; </li>
<li>如果协商缓存命中,请求响应返回的http状态为<code>304</code> 并且会显示一个<code>Not Modified(未修改的)</code>的字符串</li>
</ul>
</blockquote>
<h4 id="①-Last-Modified，If-Modified-Since"><a href="#①-Last-Modified，If-Modified-Since" class="headerlink" title="①  Last-Modified，If-Modified-Since"></a>①  Last-Modified，If-Modified-Since</h4><blockquote>
<ol>
<li><code>Last-Modified</code>表示本地文件最后修改日期</li>
</ol>
<ul>
<li>浏览器会在request header 加上 <code>If-Modified-Since</code>(上此返回的<code>Last-Modified</code>的值)</li>
<li>询问服务器在该日期后资源是否有更新</li>
<li>有更新的话就会将新的资源发送过来</li>
</ul>
<ol start="2">
<li>但如果在本地打开缓存文件,就会造成<code>Last-Modified</code>的修改,所以在HTTP1.1中出现了<code>Etag</code></li>
<li>当资源过期时（使用<code>Cache-Control</code>标识的max-age/s-maxage）</li>
</ol>
<ul>
<li>发现资源具有<code>Last-Msodified</code>声明，则向服务器请求时带上头 <code>If-Modified-Since</code>（即响应头中的<code>Last-Modified</code>值），表示请求时间。</li>
<li>这个时候服务器收到请求后发现有头<code>If-Modified-Since</code>则与<strong>被请求资源</strong>的最后修改时间进行比对</li>
<li>若最后修改时间较新，说明资源有被改动过，将新资源返回并返回状态<code>200</code>，否则返回<code>304</code>表示资源没被更新使用缓存即可。</li>
</ul>
</blockquote>
<h4 id="②-ETag、If-None-Match"><a href="#②-ETag、If-None-Match" class="headerlink" title="② ETag、If-None-Match"></a>② ETag、If-None-Match</h4><blockquote>
<ol>
<li><code>Etag</code>就行是一个直问,资源变化都会导致Etag变化,跟最后修改时间没有关系,Etag可以保证每一个资源都是唯一的</li>
<li>当资源过期时（使用Cache-Control标识的max-age/s-maxage）</li>
</ol>
<ul>
<li>发现资源具有<code>Etage</code>声明，则向服务器请求时带上头<code>If-None-Match</code>（即响应头中<code>Etag</code>的值）</li>
<li>服务器收到请求后发现有头<code>If-None-Match</code> 则与被请求资源的相应校验串进行比对</li>
<li>决定返回200或304（<strong>注意：服务器会优先验证If-None-Match</strong>）</li>
</ul>
<h6 id="两者优先级"><a href="#两者优先级" class="headerlink" title="两者优先级?"></a>两者优先级?</h6><blockquote>
<p><strong><code>ETag</code>的优先级比<code>Last-Modified</code>更高</strong></p>
</blockquote>
<blockquote>
<p>具体为什么要用<code>ETag</code>，主要出于下面几种情况考虑：</p>
</blockquote>
<blockquote>
<ul>
<li>一些文件也许会周期性的更改,但是它的内容并不会改变(仅仅只改变了修改时间),这种时候我们并不希望客户端认为这个文件被修改了,而重新GET</li>
<li>某些文件修改非常频繁,比如在秒以下的时间内进行修改(比如说1s内修改了N次),而其他方法检查到的粒度是s级的,这种修改无法判断</li>
<li>某些服务器不能精确的得到文件的最后修改时间</li>
</ul>
</blockquote>
<h6 id="服务端返回-304-流程图"><a href="#服务端返回-304-流程图" class="headerlink" title="服务端返回 304 流程图"></a>服务端返回 304 流程图</h6><p><img src="/2021/11/23/liu-lan-qi-huan-cun-ji-zhi-qiang-huan-cun-xie-shang-huan-cun/5.png" alt="304流程图"></p>
</blockquote>
<h3 id="Ⅲ-强缓存与协商缓存简单异同点"><a href="#Ⅲ-强缓存与协商缓存简单异同点" class="headerlink" title="Ⅲ -强缓存与协商缓存简单异同点"></a>Ⅲ -强缓存与协商缓存简单异同点</h3><blockquote>
<ul>
<li><strong>相同点</strong>: 如果命中,都是从客户端缓存中加载资源,而不是从服务器加载资源数据</li>
<li><strong>不同点</strong>: 强缓存不发送请求到服务器,协商缓存会发送请求到服务器</li>
</ul>
</blockquote>
<h2 id="4、常见几种状态码的区别"><a href="#4、常见几种状态码的区别" class="headerlink" title="4、常见几种状态码的区别"></a>4、常见几种状态码的区别</h2><blockquote>
<p>缓存中: 200状态码总是强缓存, 304总是协商缓存</p>
<ul>
<li><code>200</code>: 强缓存<code>expires/Cache-Control</code>失效时,返回新的资源文件</li>
<li><code>200(form cache)</code>: 强缓存两者都存在且未过期; <code>Cache-Control</code> 优先<code>Expirs</code>(默认就是这个优先级)时–&gt;浏览器从本地获取资源成功  (这个状态还能更详细分类,在下面再给出详解)</li>
<li><code>304(Not Modified)</code>:协商缓存<code>Last-modified/Etag</code>没有过期时,服务端返回状态码304 </li>
</ul>
<h6 id="这里给出个截图-安装了中文包-所以显示的中文"><a href="#这里给出个截图-安装了中文包-所以显示的中文" class="headerlink" title="这里给出个截图(安装了中文包,所以显示的中文)"></a>这里给出个截图(安装了中文包,所以显示的中文)</h6><p><img src="/2021/11/23/liu-lan-qi-huan-cun-ji-zhi-qiang-huan-cun-xie-shang-huan-cun/6.png" alt="例子"> </p>
</blockquote>
<h2 id="5、缓存位置"><a href="#5、缓存位置" class="headerlink" title="5、缓存位置"></a>5、缓存位置</h2><blockquote>
<h6 id="强缓存我们会把资源放在-memory-cache-内存缓存-和disk-cache-磁盘缓存-中-那么他们的区别在哪呢-为何要如此区分"><a href="#强缓存我们会把资源放在-memory-cache-内存缓存-和disk-cache-磁盘缓存-中-那么他们的区别在哪呢-为何要如此区分" class="headerlink" title="强缓存我们会把资源放在 memory cache(内存缓存)和disk cache(磁盘缓存) 中,那么他们的区别在哪呢?为何要如此区分?"></a>强缓存我们会把资源放在 <code>memory cache(内存缓存)</code>和<code>disk cache(磁盘缓存)</code> 中,那么他们的区别在哪呢?为何要如此区分?</h6><p><img src="/2021/11/23/liu-lan-qi-huan-cun-ji-zhi-qiang-huan-cun-xie-shang-huan-cun/6.png" alt="例子"></p>
<ul>
<li>存储图像和网页等资源主要存储在<code>disk cache(磁盘存储)</code></li>
<li>操作系统缓存文件等资源大部分都会缓存在<code>memory cache</code>中</li>
<li>具体操作浏览器自动分配,看谁的资源利用率不高就给谁</li>
<li>查找浏览器缓存时会按照 <code>Service Worker</code> –&gt; <code>Memory Cache</code> –&gt; <code>Disk Cache</code> –&gt;  <code>Push Cache</code></li>
</ul>
</blockquote>
<h3 id="Ⅰ-Service-Worker"><a href="#Ⅰ-Service-Worker" class="headerlink" title="Ⅰ -  Service Worker"></a>Ⅰ -  Service Worker</h3><blockquote>
<ul>
<li>是运行在浏览器背后的独立线程,一般可以用来实现缓存功能. </li>
<li>使用<code>Service Worker</code> 的话,因为其中涉及到请求拦截,所以传输协议必须为<code>HTTPS</code>来保障安全</li>
<li><code>Service Worker</code>的缓存和浏览器其他内建的缓存机制不同,它可以让我们自由控制缓存那些文件,如何匹配缓存、读取缓存,并且缓存时持续性的</li>
</ul>
</blockquote>
<h3 id="Ⅱ-Memory-Cache"><a href="#Ⅱ-Memory-Cache" class="headerlink" title="Ⅱ - Memory Cache"></a>Ⅱ - Memory Cache</h3><blockquote>
<ul>
<li><strong>内存中的缓存</strong>: 主要包含的是当前页面中已经抓取到的资源: 例如页面下载的样式、脚本、图片等</li>
<li>读取 <strong>内存</strong> 中的数据肯定比 <strong>磁盘</strong> 的快</li>
<li><strong>内存缓存</strong> 虽然读取高效,但是缓存持续性很短,会随着进程的释放而释放: 如我们关闭了tab页面 ,内存中的缓存也就被释放了 </li>
</ul>
</blockquote>
<h3 id="Ⅲ-Disk-Cache"><a href="#Ⅲ-Disk-Cache" class="headerlink" title="Ⅲ -  Disk Cache"></a>Ⅲ -  Disk Cache</h3><blockquote>
<ul>
<li>存储在 <strong>硬盘</strong> 中的缓存,读取速度慢点,但是什么都能存储到磁盘中,比之 <code>Memory Cache</code> 胜在容量和存储时效性上</li>
<li>在所有浏览器缓存中,<code>Disk Cache</code>覆盖面基本是最大的</li>
<li>他会根据 <code>HTTP Header</code> 中的字段判断哪些资源需要缓存,哪些资源可以不请求直接使用,哪些资源已经过期需要重新请求</li>
<li>并且即便在跨站点的情况下,相同地址的资源一旦被硬盘缓存下来,就不会再去请求数据,绝大部分数据都来自<code>Disk Cache</code></li>
<li><strong>磁盘缓存</strong> 比 <strong>内存缓存</strong> 慢的多</li>
</ul>
<h6 id="举个🌰"><a href="#举个🌰" class="headerlink" title="举个🌰"></a>举个🌰</h6><blockquote>
<p>从远程 Web 服务器直接提取访问文件可能需要 <strong>500毫秒(半秒)</strong>, 那么磁盘访问可能需要 <strong>10~20毫秒</strong> ; 而内存访问可能只需要 <strong>100纳秒</strong>; 更高级的还有 <strong>L1缓存访问</strong> 只需要0.5纳秒 (最快和最小的CPU缓存,详见此笔记 <a target="_blank" rel="noopener" href="https://gitee.com/hongjilin/hongs-study-notes/blob/master/%E7%BC%96%E7%A8%8B_%E7%AE%97%E6%B3%95%E5%8F%8A%E8%AF%BE%E7%A8%8B%E5%9F%BA%E7%A1%80%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BB%84%E6%88%90%E5%8E%9F%E7%90%86/%E7%BC%93%E5%AD%98%E3%80%81%E5%86%85%E5%AD%98%E3%80%81CPU%E7%9F%A5%E8%AF%86%E7%82%B9%E8%A7%A3%E6%9E%90%E7%AC%94%E8%AE%B0.md#%E5%9B%9Bcpu%E7%9A%84%E5%A4%9A%E7%BA%A7%E7%BC%93%E5%AD%98%E9%AB%98%E9%80%9F%E7%BC%93%E5%AD%98">缓存、内存、CPU知识点解析</a> )</p>
</blockquote>
</blockquote>
<h3 id="Ⅳ-prefetch-cache-预取缓存"><a href="#Ⅳ-prefetch-cache-预取缓存" class="headerlink" title="Ⅳ -  prefetch cache(预取缓存)"></a>Ⅳ -  prefetch cache(预取缓存)</h3><blockquote>
<ul>
<li><strong>link</strong> 标签带上 <strong>prefetch</strong> ,再次加载时会出现</li>
<li><code>prefetch</code> 是 <strong>预加载</strong> 的一种方式: 被标记为 <code>prefetch</code> 的资源,将会被浏览器在空闲时间加载</li>
</ul>
</blockquote>
<h3 id="Ⅴ-Push-Cache"><a href="#Ⅴ-Push-Cache" class="headerlink" title="Ⅴ -  Push Cache"></a>Ⅴ -  Push Cache</h3><blockquote>
<ul>
<li><code>Push Cache(推送缓存)</code> 是 <strong>HTTP/2</strong> 中的内容,当以上三种缓存都没有命中时,它才会被使用</li>
<li>它只在 <strong>会话 (Session)</strong> 中存在,一旦会话结束就会被释放,并且缓存时间也会很短暂</li>
<li>在Chrome浏览器中只有 <strong>5分钟</strong> 左右,同时它也并非严格执行HTTP头中的缓存指令</li>
</ul>
</blockquote>
<h3 id="Ⅵ-CPU、内存、硬盘概述"><a href="#Ⅵ-CPU、内存、硬盘概述" class="headerlink" title="Ⅵ -  CPU、内存、硬盘概述"></a>Ⅵ -  CPU、内存、硬盘概述</h3><blockquote>
<h6 id="可能有小伙伴对于此处知识点没什么直观的概念-此处给出一个大概叙述-想了解更多的话此部分知识点本人有专门梳理笔记文件"><a href="#可能有小伙伴对于此处知识点没什么直观的概念-此处给出一个大概叙述-想了解更多的话此部分知识点本人有专门梳理笔记文件" class="headerlink" title="可能有小伙伴对于此处知识点没什么直观的概念,此处给出一个大概叙述; 想了解更多的话此部分知识点本人有专门梳理笔记文件"></a>可能有小伙伴对于此处知识点没什么直观的概念,此处给出一个大概叙述; 想了解更多的话此部分知识点本人有专门梳理笔记文件</h6><h6 id="–-gt-点我传送"><a href="#–-gt-点我传送" class="headerlink" title="–&gt; 点我传送"></a>–&gt; <a target="_blank" rel="noopener" href="https://gitee.com/hongjilin/hongs-study-notes/blob/master/%E7%BC%96%E7%A8%8B_%E7%AE%97%E6%B3%95%E5%8F%8A%E8%AF%BE%E7%A8%8B%E5%9F%BA%E7%A1%80%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BB%84%E6%88%90%E5%8E%9F%E7%90%86/%E7%BC%93%E5%AD%98%E3%80%81%E5%86%85%E5%AD%98%E3%80%81CPU%E7%9F%A5%E8%AF%86%E7%82%B9%E8%A7%A3%E6%9E%90%E7%AC%94%E8%AE%B0.md">点我传送</a></h6><ul>
<li>CPU、内存、硬盘都是计算机的主要组成部分</li>
<li><strong>CPU</strong>: 中央处理单元的缩写,也叫做 <code>处理器</code>,是计算机的运算核心和控制核心; 电脑靠CPU来运算、控制. 让电脑各个部件顺利工作,起到协调作用</li>
<li><strong>硬盘</strong>: 存储资料和软件等数据的设备,有容量大、断电数据不丢失的特点</li>
<li><strong>内存</strong>: 负责 <strong>硬盘</strong> 等硬件上的数据与 <strong>CPU</strong> 之间数据的交换处理. 特点是: <code>体积小</code>、<code>速度快</code>、<code>有电可存</code>、<code>无电清空</code>,即电脑在开机状态时内存中可存储数据,关机后将自动清空其中的所有数据</li>
</ul>
</blockquote>
<h2 id="6、强缓存有协商缓存的区别"><a href="#6、强缓存有协商缓存的区别" class="headerlink" title="6、强缓存有协商缓存的区别"></a>6、强缓存有协商缓存的区别</h2><blockquote>
<p>这里再次总结整理一下两者之间的区别</p>
<ul>
<li>强缓存不发请求到服务端,所以有时候资源更新了浏览器还不知道; </li>
<li>但是协商缓存会发请求到服务器,所以资源是否更新,服务器肯定知道</li>
<li>大部分web服务器都默认开启协商缓存</li>
</ul>
</blockquote>
<h2 id="7、刷新对于强缓存和协商缓存的影响"><a href="#7、刷新对于强缓存和协商缓存的影响" class="headerlink" title="7、刷新对于强缓存和协商缓存的影响"></a>7、刷新对于强缓存和协商缓存的影响</h2><blockquote>
<ul>
<li>当 <code>ctrl+F5</code>强制刷新网页时: 直接从服务器加载, <strong>跳过强缓存和协商缓存</strong></li>
<li>当 f5 刷新网页时,跳过强缓存,但是会检查协商缓存</li>
<li>浏览器地址写入URL并回车: 浏览器发现缓存中有这个文件了,就不用继续请求了,直接去缓存拿 (最快)</li>
</ul>
</blockquote>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">ZY Shen</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://shenzy98.gitee.io/2021/11/23/liu-lan-qi-huan-cun-ji-zhi-qiang-huan-cun-xie-shang-huan-cun/">https://shenzy98.gitee.io/2021/11/23/liu-lan-qi-huan-cun-ji-zhi-qiang-huan-cun-xie-shang-huan-cun/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">ZY Shen</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C/">
                                    <span class="chip bg-color">计算机网络</span>
                                </a>
                            
                                <a href="/tags/%E5%BC%BA%E7%BC%93%E5%AD%98-%E5%8D%8F%E5%95%86%E7%BC%93%E5%AD%98/">
                                    <span class="chip bg-color">强缓存&amp;协商缓存</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/11/24/jian-zhi-offer-part5/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/19.jpg" class="responsive-img" alt="《剑指offer》part5">
                        
                        <span class="card-title">《剑指offer》part5</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-11-24
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%89%91%E6%8C%87offer/" class="post-category">
                                    剑指offer
                                </a>
                            
                            <a href="/categories/%E5%89%91%E6%8C%87offer/%E7%AE%97%E6%B3%95/" class="post-category">
                                    算法
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                    <a href="/tags/%E5%89%91%E6%8C%87offer/">
                        <span class="chip bg-color">剑指offer</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/11/05/7-chong-chang-yong-pai-xu-suan-fa-ji-yu-js-shi-xian-dai-ma/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/2.jpg" class="responsive-img" alt="7种常用排序算法 -- 基于JS实现代码">
                        
                        <span class="card-title">7种常用排序算法 -- 基于JS实现代码</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-11-05
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%89%8D%E7%AB%AF%E7%AC%94%E8%AE%B0/" class="post-category">
                                    前端笔记
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                    <a href="/tags/%E6%8E%92%E5%BA%8F/">
                        <span class="chip bg-color">排序</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="song"
                   id="16494352"
                   fixed='true'
                   autoplay='true'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='false'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2022</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">ZY Shen</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">34.6k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Usageforshen" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:734586480@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=734586480" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 734586480" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>



<!-- 在主题的 _config.yml 文件中，默认支持 QQ、GitHub 和邮箱等的配置，你可以在主题文件的 /layout/_partial/social-link.ejs 文件中，新增、修改你需要的社交链接地址，增加链接可参考如下代码： -->

    <a href="https://github.com/Usageforshen" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>
</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
